/*******************************************************************************
 * Copyright (c) 2006 CEA List.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA List - initial API and implementation
 *******************************************************************************/
package com.cea.papyrus.diagram.classdiagram.tabbedproperties.composite;

import java.util.Iterator;
import java.util.List;

import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CommandStack;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.uml2.common.edit.command.ChangeCommand;
import org.eclipse.uml2.uml.Behavior;

import com.cea.papyrus.core.PapyrusPlugin;
import com.cea.papyrus.core.commands.EMFtoGEFWrapCommand;
import com.cea.papyrus.core.commands.MoveInListCommand;
import com.cea.papyrus.core.commands.UMLElementCreateCommand;
import com.cea.papyrus.core.commands.factories.UMLDi2ElementDeleteFactory;
import com.cea.papyrus.core.editor.CommandStackUtils;
import com.cea.papyrus.core.tabbedproperties.composite.DecoratedTableComposite;
import com.cea.papyrus.core.tabbedproperties.composite.ISectionComposite;
import com.cea.papyrus.core.ui.dialogs.ExtendedDirectEditionDialog;
import com.cea.papyrus.extensionpoints.editors.configuration.IDirectEditorConfiguration;
import com.cea.papyrus.extensionpoints.editors.utils.DirectEditorsUtil;
import com.cea.papyrus.umlutils.Element;
import com.cea.papyrus.umlutils.Parameter;

/**
 * Composite that displays the parameters of a behavior.
 */
public class BehaviorParametersComposite extends DecoratedTableComposite implements ISectionComposite {

	/**
	 * Default Constructor.
	 */
	public BehaviorParametersComposite() {
		super("Parameters");
	}

	/**
	 * key to access UML Data from table items.
	 */ 
	private final static String KEY = "parameter_data";
	
	/**
	 * Behavior for which methods are displayed.
	 */
	private Behavior behavior;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setElement(Element element) {
		super.setElement(element);
		this.behavior = (Behavior)element.getUml2Element();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void refresh() {
		if( !table.isDisposed()&& (behavior!=null)){
			// Remove parameters from table 
			table.removeAll();

			// Read and add parameter
			Iterator<org.eclipse.uml2.uml.Parameter> it = behavior.getOwnedParameters().iterator();
			while (it.hasNext()) {
				Parameter parameter = new com.cea.papyrus.umlutils.Parameter(it.next());
				TableItem item = new TableItem(table, SWT.BORDER);
				item.setImage(PapyrusPlugin.getImage(PapyrusPlugin.UML_ICONS_16x16+"Parameter.gif"));
				item.setData(KEY, parameter);
				item.setText(parameter.getLabel());
			}
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void addButtonPressed() {
		Command command = new UMLElementCreateCommand(org.eclipse.uml2.uml.Parameter.class, behavior);
		CommandStack stack = CommandStackUtils.getCommandStack();
		assert (stack!=null) : "Impossible to adapt current editor into a CommandStack";
		stack.execute(command);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void downButtonPressed() {
		CompoundCommand compoundCommand = new CompoundCommand();
		TableItem[] tableItems = table.getSelection();

		for(int i = (tableItems.length-1); i >= 0; i--) {
			// get parameters list
			List<org.eclipse.uml2.uml.Parameter> parameters = behavior.getOwnedParameters();
			// get parameter
			org.eclipse.uml2.uml.Parameter parameter = ((Parameter) tableItems[i].getData(KEY)).getUml2Parameter();
			int newIndex = table.indexOf(tableItems[i]) + 1;
			if(newIndex < parameters.size()) {
				//new MoveInListCommand(parameters, parameter, newIndex).execute();
				compoundCommand.add(new MoveInListCommand(parameters, parameter, newIndex));
			}
		}
		CommandStack stack = CommandStackUtils.getCommandStack();
		assert (stack!=null) : "Impossible to adapt current editor into a CommandStackUtils";
		stack.execute(compoundCommand);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void editItem(TableItem item) {
		if (item == null) {
			return;
		}

		// parameter linked to the item
		final Parameter parameter = (Parameter)item.getData(KEY);

		// getEditor for this language
		final IDirectEditorConfiguration configuration = DirectEditorsUtil.findEditorConfiguration("UML", "org.eclipse.uml2.uml.Parameter"); 
		configuration.setLanguage("UML");
		configuration.preEditAction(parameter.getUml2Parameter());
		final ExtendedDirectEditionDialog dialog = new ExtendedDirectEditionDialog(table.getShell(),
				parameter.getUml2Parameter(),
				configuration.getTextToEdit(parameter.getUml2Parameter()),
				configuration);
		if(Window.OK==dialog.open()) {
			// apply modifications
			final AdapterFactoryEditingDomain emfDomain = getModelManager().getDiResourceSet().getEditingDomain();
			EMFtoGEFWrapCommand command = new EMFtoGEFWrapCommand(emfDomain) {
				@Override
				public org.eclipse.emf.common.command.Command createEMFCommand() {
					return new ChangeCommand(emfDomain, new Runnable() {
						public void run() {configuration.postEditAction(parameter.getUml2Parameter(), dialog.getValue());};
					}, "Edit Label", "Edit the label of the selected element");
				}
			};
			CommandStackUtils.getCommandStack().execute(command);
		}
		refresh();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void removeButtonPressed() {
		CompoundCommand command = new CompoundCommand(); 
		// get selection and delete it
		TableItem[] tableItems = table.getSelection();
		for(int i = 0; i < tableItems.length ; i++) {
			// get parameter
			Parameter parameter = (Parameter) tableItems[i].getData(KEY);
			command.add(UMLDi2ElementDeleteFactory.eINSTANCE.createCommand(parameter.getUml2Parameter()));
		}
		CommandStack stack = CommandStackUtils.getCommandStack();
		assert (stack!=null) : "Impossible to adapt current editor into a CommandStackUtils";
		stack.execute(command);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void upButtonPressed() {
		CompoundCommand compoundCommand = new CompoundCommand();
		TableItem[] tableItems = table.getSelection();
		List<org.eclipse.uml2.uml.Parameter> parameters = behavior.getOwnedParameters();
		for(int i = 0; i < tableItems.length ; i++) {
			// get parameter
			org.eclipse.uml2.uml.Parameter parameter = ((Parameter) tableItems[i].getData(KEY)).getUml2Parameter();
			int newIndex = table.indexOf(tableItems[i]) - 1;
			if (newIndex >= 0) {
				compoundCommand.add(new MoveInListCommand(parameters, parameter, newIndex));
			}
		}
		CommandStack stack = CommandStackUtils.getCommandStack();
		assert (stack!=null) : "Impossible to adapt current editor into a CommandStackUtils";
		stack.execute(compoundCommand);
	}
}
